<template>
  <div class="app-container">
    <el-input v-model="filterText" placeholder="Filter keyword" style="margin-bottom:30px;"/>

    <el-button @click="addRootNode" style="margin-bottom: 20px;">添加根节点</el-button>

    <el-tree
      ref="tree2"
      :data="subjectList"
      :props="defaultProps"
      :filter-node-method="filterNode"
      class="filter-tree"
      default-expand-all
      @node-contextmenu="handleNodeContextMenu"
    />

    <!-- 右键菜单 -->
    <div 
      v-show="contextMenuVisible" 
      :style="{left: contextMenuLeft + 'px', top: contextMenuTop + 'px'}" 
      class="context-menu"
    >
      <div class="menu-item" @click="addNode">新增节点</div>
      <div class="menu-item" @click="deleteNode">删除节点</div>
    </div>

    <!-- 新增/编辑节点对话框 -->
    <el-dialog :visible.sync="dialogFormVisible" :title="dialogTitle">
      <el-form :model="formData">
        <el-form-item label="分类名称">
          <el-input v-model="formData.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类ID">
          <el-input v-model="formData.id" :disabled="!!formData.parentId || isRootNode" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveNode">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import subject from '@/api/edu/subject'

  export default {

    data() {
      return {
        filterText: '',
        subjectList: [],
        defaultProps: {
          children: 'children',
          label: 'title'
        },
        // 右键菜单相关
        contextMenuVisible: false,
        contextMenuLeft: 0,
        contextMenuTop: 0,
        // 当前选中节点
        currentNode: null,
        currentNodeData: null,
        // 对话框相关
        dialogFormVisible: false,
        dialogTitle: '',
        isRootNode: false, // 是否为根节点
        formData: {
          id: '',
          title: '',
          parentId: ''
        }
      }
    },
    watch: {
      filterText(val) {
        this.$refs.tree2.filter(val)
      }
    },
    created() {
      this.fetchNodeList()
    },
    mounted() {
      // 点击其他地方隐藏菜单
      document.addEventListener('click', this.hideContextMenu)
    },
    beforeDestroy() {
      document.removeEventListener('click', this.hideContextMenu)
    },
    methods: {
      //获取list
      fetchNodeList() {
        subject.getNestedTreeList().then(response => {
          if (response.success === true) {
            this.subjectList = response.data
          }
        })
      },
      //搜索节点
      filterNode(value, data) {
        if (!value) return true
        return data.title.toLowerCase().indexOf(value.toLowerCase()) !== -1
      },
      // 处理节点右键事件
      handleNodeContextMenu(event, data, node) {
        event.preventDefault()
        this.currentNode = node
        this.currentNodeData = data
        this.contextMenuLeft = event.clientX
        this.contextMenuTop = event.clientY
        this.contextMenuVisible = true
      },
      // 隐藏右键菜单
      hideContextMenu() {
        this.contextMenuVisible = false
      },
      // 添加根节点
      addRootNode() {
        this.isRootNode = true
        this.dialogTitle = '新增根节点'
        this.formData = {
          id: '',
          title: '',
          parentId: '0' // 根节点的parentId为0
        }
        this.dialogFormVisible = true
      },
      // 新增节点
      addNode() {
        this.hideContextMenu()
        this.isRootNode = false
        this.dialogTitle = '新增分类'
        this.formData = {
          id: '',
          title: '',
          parentId: this.currentNodeData.id
        }
        this.dialogFormVisible = true
      },
      // 删除节点
      deleteNode() {
        this.hideContextMenu()
        const nodeId = this.currentNodeData.id
        // 检查nodeId是否有效
        if (!nodeId) {
          this.$message({
            type: 'error',
            message: '无效的节点ID'
          })
          return
        }
        
        this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 调用删除API
          subject.deleteSubject(nodeId).then(response => {
            if (response.success === true) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              // 重新获取数据
              this.fetchNodeList()
            } else {
              this.$message({
                type: 'error',
                message: '删除失败: ' + response.message
              })
            }
          }).catch(error => {
            console.error('删除节点失败:', error)
            this.$message({
              type: 'error',
              message: '删除失败: ' + (error.message || error)
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 保存节点
      saveNode() {
        // 构造要发送的数据
        const subjectData = {
          title: this.formData.title,
          parentId: this.formData.parentId,
          children: []
        }

        // 调用添加API
        subject.addOneSubject(subjectData).then(response => {
          if (response.success === true) {
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
            this.dialogFormVisible = false
            // 重新获取数据
            this.fetchNodeList()
          } else {
            this.$message({
              type: 'error',
              message: '添加失败: ' + response.message
            })
          }
        }).catch(error => {
          this.$message({
            type: 'error',
            message: '添加失败: ' + error
          })
        })
      }
    }
  }
</script>
<style scoped>
::v-deep .el-tree-node__label {
    width: auto;
    float: right;
    font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
    font-size: 14px;
    line-height: 25px;
    letter-spacing: 1px;
}
::v-deep .el-tree-node__content:hover {
    font-weight: bold;
}
 
/* 右键菜单样式 */
.context-menu {
  position: fixed;
  z-index: 9999;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 5px 0;
}

.menu-item {
  padding: 7px 16px;
  cursor: pointer;
  font-size: 14px;
}

.menu-item:hover {
  background: #f5f5f5;
}
</style>